package com.im.imservice.config;

import com.im.imservice.enity.Client;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Huawei
 * @date 2023-08-11 14:59
 */
public class CurrentChannelInfo {

    private static Map<String, Channel> channelGroupMap = new ConcurrentHashMap<>();

    /**
     * 根据用户获取该用户的通道
     * @param userId 判断接收人id
     * @return
     */
    public static Channel getChannelGroupMap(String userId){
        return channelGroupMap.get(userId);
    }

    /**
     * 根据接口用户获取该用户的通道，判断接收人是否在线
     * @param userId 接收用户id
     * @return
     */
    public static Boolean containsKey(String userId){
        return channelGroupMap.containsKey(userId);
    }


    /**
     * 存储用户获取该用户的通道
     * @param userId
     * @return
     */
    public static void setChannelGroupMap(String userId,Channel channel){
        AttributeKey<String> key = AttributeKey.valueOf(channel.id().asLongText());
        channel.attr(key).set(userId);
        channelGroupMap.put(userId,channel);
    }

    /**
     * 删除当前通道关联的用户id,并且删除存储的用户id
     * @param channel 通道
     * @return
     */
    public static void deleteChannel(Channel channel){
        AttributeKey<String> key = AttributeKey.valueOf(channel.id().asLongText());
        String userId = channel.attr(key).get();
        if (channel.hasAttr(key) && null != userId){
            channelGroupMap.remove(userId);
            channel.attr(key).getAndSet(null);
        }
    }

    /**
     * 获取当前通道关联的用户id
     * AttributeKey会为每一个通道生成一个唯一的通道Id,连接时用户通道Id存储对应的用户id
     * @param channel
     * @return
     */
    public static String getChannelUserId(Channel channel){
        AttributeKey<String> key = AttributeKey.valueOf(channel.id().asLongText());
        return channel.attr(key).get();
    }
}
